#include "mutexlist.h"

void initialize_MutexList(MutexList *mutexlist, const int maxSocket)
{
    initialize_List(&(mutexlist->fileSocket),create_IntList,delete_IntList, NULL, NULL);
    mutexlist->maxSocket = maxSocket;
    mutexlist->nbSocketConnect = 0;
    pthread_mutex_init(&(mutexlist->mutexAcces), NULL);
    pthread_cond_init(&(mutexlist->condVide), NULL);
}

void testament_MutexList(MutexList *mutexlist)
{
    testament_List(&(mutexlist->fileSocket));
    pthread_mutex_destroy(&(mutexlist->mutexAcces));
    pthread_cond_destroy(&(mutexlist->condVide));
}

MutexListReturn insert_MutexList(MutexList *mutexlist, const Element element)
{
    pthread_mutex_lock(&(mutexlist->mutexAcces));
    
    if(insertLast_List(&(mutexlist->fileSocket), element) == LIST_ERR)
      {
	pthread_mutex_unlock(&(mutexlist->mutexAcces));
	return MUTEXLIST_ERR;
      }
    pthread_cond_signal(&(mutexlist->condVide));

    pthread_mutex_unlock(&(mutexlist->mutexAcces));

    return MUTEXLIST_SUCCESS;

}

int getFirst_MutexList(MutexList *mutexlist)
{
    int *s;
    int res;

    pthread_mutex_lock(&(mutexlist->mutexAcces));

    while(getSize_List(&(mutexlist->fileSocket))==0)
    {
      if(CONTINUE_SERVER)
        pthread_cond_wait(&(mutexlist->condVide),&(mutexlist->mutexAcces));
      else
	{
	  pthread_mutex_unlock(&(mutexlist->mutexAcces));
	  return MUTEXLIST_END;
	}
    }

    s=getDataFirst_List(&(mutexlist->fileSocket));
    res=(*s);
    
    deleteFirst_List(&(mutexlist->fileSocket));

    pthread_mutex_unlock(&(mutexlist->mutexAcces));

    return res;

}

void notifyEnd_MutexList(MutexList *mutexlist)
{
  pthread_cond_broadcast(&(mutexlist->condVide));
}

void addConnection_MutexList(MutexList *mutexlist)
{
    pthread_mutex_lock(&(mutexlist->mutexAcces));
    mutexlist->nbSocketConnect ++;
    pthread_mutex_unlock(&(mutexlist->mutexAcces));
}

void subtractConnection_MutexList(MutexList *mutexlist)
{
    pthread_mutex_lock(&(mutexlist->mutexAcces));
    mutexlist->nbSocketConnect --;
    pthread_mutex_unlock(&(mutexlist->mutexAcces));
}

int getConnection_MutexList(MutexList *mutexlist)
{
  int ret = MUTEXLIST_SUCCESS;
  pthread_mutex_lock(&(mutexlist->mutexAcces));
  if(mutexlist->nbSocketConnect >= mutexlist->maxSocket)
    ret = MUTEXLIST_MAX;
  pthread_mutex_unlock(&(mutexlist->mutexAcces));
  return ret;
}
